﻿using System;
using System.Data;
using Billing2.cls;
using MyLib;
using System.Configuration;

namespace Billing2
{
    public partial class ChangeRequestBatch : System.Web.UI.Page
    {        
        public bool Read0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xRead0"]);
            }
            set
            {
                this.ViewState["xRead0"] = value;
            }
        }

        public bool Create0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xCreate0"]);
            }
            set
            {
                this.ViewState["xCreate0"] = value;
            }
        }

        public bool Update0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xUpdate0"]);
            }
            set
            {
                this.ViewState["xUpdate0"] = value;
            }
        }

        public bool Delete0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xDelete0"]);
            }
            set
            {
                this.ViewState["xDelete0"] = value;
            }
        }

        public string CsvFilename
        {
            get
            {
                return Convert.ToString(this.ViewState["CsvFilename"]);
            }
            set
            {
                this.ViewState["CsvFilename"] = value;
            }
        }

        private ClsChangeRequestHelper.ChangeRequestType ChangeRequestType
        {
            get
            {
                return (ClsChangeRequestHelper.ChangeRequestType)int.Parse(this.xChangeRequestType.Value);
            }
            set
            {
                this.xChangeRequestType.Value = ((Int64)value).ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Session["SiteID"] == null)
                this.Response.Redirect("default.aspx", true);
            try
            {
                this.ucHighlight1.CloseAll();
                if (this.Page.IsPostBack)
                    return;
                DataTable dataTable = new ClsUserProfile()
                {
                    ID = Convert.ToInt64(LoginUser.UserID)
                }.Select();

                this.ChangeRequestType = (ClsChangeRequestHelper.ChangeRequestType)(int.Parse(((NewChangeRequest)this.PreviousPage).ChangeRequestType));
                this.Create0 = ((NewChangeRequest)this.PreviousPage).Create0;
                this.Update0 = ((NewChangeRequest)this.PreviousPage).Update0;
                this.Delete0 = ((NewChangeRequest)this.PreviousPage).Delete0;
                this.Read0 = ((NewChangeRequest)this.PreviousPage).Read0;
                this.CsvFilename = "";
                this.lbl_current_filename.Visible = false;
                this.cb_create_cr_record.Checked = true;
                this.cb_create_cr_record.Enabled = false;
                this.BtnSubmit.Visible = false;
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error("Exception:\r\n Type:" + ex.GetType() + ";\r\n Message:" + ex.Message + ";\r\n Trace:" + ex.StackTrace);
            }
        }

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ViewStateUserKey = Session.SessionID;
        }

        protected void btn_upload_Click(object sender, EventArgs e)
        {

        }

        protected void btn_preview_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.PostedFile == null || this.FileUpload1.PostedFile.ContentLength == 0)
            {
                this.ucHighlight1.ErrorMessage = "Please select file to upload";
                return;
            }
            if (this.FileUpload1.PostedFile.ContentLength > 1024 * 1024)
            {
                this.ucHighlight1.ErrorMessage = "File size must less than 1MB!";
                return;
            }

            string fileName = Common.EscapeFilename(System.IO.Path.GetFileName(this.FileUpload1.PostedFile.FileName));
            string fileExtension = System.IO.Path.GetExtension(fileName);
            if (fileExtension.ToLower() != ".csv")
            {
                EPPLog.Logger.Debug("fileExtension: " + fileExtension);
                this.ucHighlight1.ErrorMessage = "File format must be 'csv'!";
                return;
            }

            try
            {
                this.CsvFilename = System.Web.HttpContext.Current.Request.MapPath("import/") + DateTime.Now.ToString("yyyyMMdd") + "_" + Common.EscapeFilename(fileName);
                this.FileUpload1.PostedFile.SaveAs(this.CsvFilename);
                this.lbl_current_filename.Text = "Current File Name: " + Common.HtmlEncode(System.IO.Path.GetFileName(Common.EscapeFullFileName(this.CsvFilename)));
                this.lbl_current_filename.Visible = true;
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex.Message);
                this.ucHighlight1.ErrorMessage = "File format must be 'CSV'!";
                return;
            }

            try
            {
                ClsImportSubscriber import = new ClsImportSubscriber(this.ChangeRequestType);
                DateTime default_start_date = tb_default_start_date.Text.Trim() == "" ? DateTime.MinValue : Convert.ToDateTime(tb_default_start_date.Text);
                import.Preview(this.CsvFilename, ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(), default_start_date);
                if (import.error > 0)
                {
                    this.ucHighlight1.ErrorMessage = Microsoft.Security.Application.Encoder.HtmlEncode(import.Message).Replace("&#13;&#10;", "<br />");
                    this.BtnSubmit.Visible = false;
                }
                else
                {
                    this.ucHighlight1.Message = Microsoft.Security.Application.Encoder.HtmlEncode(import.Message).Replace("&#13;&#10;", "<br />");
                    this.BtnSubmit.Visible = true;
                }
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex.ExceptionInfo());
                this.ucHighlight1.ErrorMessage = ex.Message;
                return;
            }
        }

        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.CsvFilename))
            {
                this.ucHighlight1.ErrorMessage = "Please upload CSV file first!";
                return;
            }
            this.ucHighlight1.ClearMessage();
            
            try
            {
                ClsImportSubscriber import = new ClsImportSubscriber(this.ChangeRequestType);
                DateTime default_start_date = tb_default_start_date.Text.Trim() == "" ? DateTime.MinValue : Convert.ToDateTime(tb_default_start_date.Text);
                bool create_cr_record = cb_create_cr_record.Checked;
                
                import.Preview(this.CsvFilename, ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(), default_start_date);
                if (import.error > 0)
                    throw new Exception(import.Message);
                if (import.organizations.Count + import.subscribers.Count == 0)
                    throw new Exception("No data to import");

                import.Submit(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(), create_cr_record);
                if (import.error > 0)
                {
                    this.ucHighlight1.ErrorMessage = Microsoft.Security.Application.Encoder.HtmlEncode(import.Message).Replace("&#13;&#10;", "<br />");
                }
                else
                {
                    this.ucHighlight1.Message = Microsoft.Security.Application.Encoder.HtmlEncode(import.Message).Replace("&#13;&#10;", "<br />");
                }
                return;
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex.ExceptionInfo());
                this.ucHighlight1.ErrorMessage = Microsoft.Security.Application.Encoder.HtmlEncode(ex.Message).Replace("&#13;&#10;", "<br />");
                return;
            }
            finally
            {
            }
        }

    }
}